package com.illtamer.infinite.collapsar.server.pop3;

import com.illtamer.infinite.collapsar.server.handler.Handler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.lang3.StringEscapeUtils;

public class POP3ServerHandler extends SimpleChannelInboundHandler<String> {

    private final TransferContext context = new TransferContext();

    private final Handler loginHandler = new POP3CommandHandler(context);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 与客户端成功建立连接，并回复状态
        channel.writeAndFlush("+OK POP3 server ready\r\n");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("接收指令：" + StringEscapeUtils.unescapeJava(msg));
        if (context.getState() == TransferContext.State.AUTHORIZATION) {
            loginHandler.handle(msg, channel);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.channel().close();
    }

}
